package com.free.bsf.metric.base;

import com.free.bsf.core.base.BsfException;
import com.free.bsf.core.util.JsonUtils;
import com.free.bsf.core.util.StringUtils;
import com.free.bsf.core.util.WebUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.val;

import javax.servlet.http.Cookie;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    public  static User getCurrent()
    {
        //Object u = WebUtils.getRequest().getSession().getAttribute("Current");
        val u =  Arrays.stream(WebUtils.getRequest().getCookies()).filter(c->"current".equals(c.getName())).findFirst();
        if (!u.isPresent()|| StringUtils.isEmpty(u.get().getValue()))
        {
            return null;
        }
        else
        {
            try {
                return JsonUtils.deserialize(DesUtil.getDecryptString(URLDecoder.decode(u.get().getValue(), "UTF-8")), User.class);//(User)u;
            }catch (Exception e){
                throw new BsfException(e);
            }
        }
    }
    public static String setCurrent(User value)
    {
        try {
            String token =null;
            if(value!=null) {
                token = URLEncoder.encode(DesUtil.getEncryptString(JsonUtils.serialize(value)), "UTF-8");
            }else {
                token=null;
            }
            WebUtils.getResponse().addCookie(new Cookie("current", token));
            return token;
            //WebUtils.getRequest().getSession().setAttribute("Current",value);
        }catch (Exception e){
            throw new BsfException(e);
        }
    }
    private String username;
    private Integer userid;
    private Integer role;
    private long loginTime=System.currentTimeMillis();
}